/**
 * node 端使用的请求
 */
var host = require('../env.config').host

var rest = require('restler')

/**
 * 从 req 中获取要配置的 header
 */
function getHeaders(req) {
  var user = req.session.user || { agentId: null, phone: null ,wechatInfoId: null}
  let agentId = user.agentId;
  let phone = user.phone;
  let wechatInfoId = user.wechatInfoId;
  return !agentId?{}:{agentId,phone,wechatInfoId}
}

function parseUrl(url, data) {
  var arr = url.split('/')
  for (var i in arr) {
    var it = arr[i]
    if (it.indexOf(':') === 0) {
      arr[i] = data['_' + it.slice(1)]
    }
  }
  return arr.join('/')
}

class Ezapi {
  constructor({ host}) {
    this.host = host
  }
  request(req, api, data, cb) {
    var url = this.host + parseUrl(api.url, data)
    var callback = function(data, res) {
      if (!data)
      {
        console.log(res);
        return cb({ code: 500 }, null)
      }
      if (data instanceof Error) return cb({ code: 500, message: data.message })
      if (data.status == 500) {
        console.log(res);
        return cb({ code: 500 }, null)
      }
      if (data.status == 400) return cb({ code: 400, message: data.message }, null)
      //-1013代表后台用户已删除,或者被其他微信登录顶调，需要清空session
      if(data.code==-1013){
        console.log("ApiService:登录失效",req.session.user)
        SessionUtil.clearLoginSession(req)
      }
      if(typeof(cb)=="function"){
        return cb(data, res)
      }
    }
    sails.log.debug(api);
    sails.log.debug(api.method, url)
    sails.log.debug('& data: ', JSON.stringify(data))

    var options = {
      data,
      headers: getHeaders(req),
      method: api.method,
      parser: rest.parsers.auto
    }
    if(api.method.toLowerCase()=="get"){
      options.query=data;
    }else{
      options.data=data;
    }
    rest.request(url, options)
      .on('complete', callback)
  }

}

module.exports = new Ezapi({ host })
